package com.example.treasure_back.websocket;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.treasure_back.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint(value = "/websocket/{userId}")
public class FriendWebSocket {

     //在线人数
    public static int onlineNumber = 0;
    //以用户的姓名为key，WebSocket为对象保存起来
    private static Map<String, FriendWebSocket> clients = new ConcurrentHashMap<>();
    //会话
    private Session session;
    // 用户名称
    private String userId;
    private static UserService userService;
    @Autowired
    public void setUserService(UserService userService){
        FriendWebSocket.userService=userService;
    }
    //建立连接
    @OnOpen
    public void onOpen(@PathParam("userId") String userId,Session session)
    {
        onlineNumber++;
        this.userId = userId;
        this.session = session;
        // 将新连接的用户加入列表中
        clients.put(userId, this);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    //连接关闭
    @OnClose
    public void onClose()
    {
        onlineNumber--;
        clients.remove(userId);
        System.out.println("有连接关闭！ 当前在线人数" + clients.size());
    }
    //收到客户端的消息
    @OnMessage
    public void onMessage(String message, Session session)
    {
        try {
            JSONObject jsonObject = JSON.parseObject(message);
            String toUserId = jsonObject.getString("friendId");
            jsonObject.put("friendId", userId);
            jsonObject.put("username", userService.getUsername(userId));
            String msg = jsonObject.toJSONString();
            sendMessageTo(msg, toUserId);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public void sendMessageTo(String message, String friendId) throws IOException {
        for (FriendWebSocket item : clients.values()) {
            // 找到要发送的用户
            if (item.userId.equals(friendId) ) {
                item.session.getAsyncRemote().sendText(message);
                break;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineNumber;
    }

}

